package com.fx.student.service.impl;

import com.fx.demo.common.resulUtils.AjaxResult;
import com.fx.demo.common.resulUtils.ResultStatus;
import com.fx.demo.common.resulUtils.ResultUtil;
import com.fx.student.dto.StudentDto;
import com.fx.student.entity.Student;
import com.fx.student.mapper.StudentMapper;
import com.fx.student.service.StudentSer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

@Service
public class StudentSerImpl implements StudentSer {
    private final Logger log= LoggerFactory.getLogger(this.getClass());
    @Autowired
    private StudentMapper dao;
    @Override
    public AjaxResult<Collection<Student>> getStudents(int pageNum, int pageSize) {
        if(pageNum<1){
            throw new IllegalArgumentException("pageNum的值应大于0,从1开始");
        }
        int start = (pageNum-1)*pageSize;
        StudentDto param=new StudentDto(start,pageSize);
        AjaxResult<Collection<Student>>ajaxResult=null;
        List<Student>students=new ArrayList<>();
        int total=dao.findPageWithCount(param);
        if(total==0){
            ajaxResult=ResultUtil.succ(students,ResultStatus.FIND_SUCC_EMPTY);
        }else{
            students=dao.findPageWithResult(param);
            ajaxResult=ResultUtil.succ(start,pageSize,total,null,students);
        }
        return ajaxResult;
    }

    @Override
    public AjaxResult<Student> getStudent(String id) {
        AjaxResult<Student>ajaxResult=null;
        Student student=dao.selectById(id);
        if(null==student){
            ajaxResult=ResultUtil.succ(null, ResultStatus.FIND_SUCC_EMPTY);
        }else{
            ajaxResult=ResultUtil.succ(student);
        }
        return ajaxResult;
    }

    @Override
    public void save(Student student) {
        if(null == student){
            log.error("未接收到Student对象");
            throw new RuntimeException("未接收到Student对象");
        }
        student.setId(UUID.randomUUID().toString().replaceAll("-",""));
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(student.getCreateTime());
        dao.insert(student);
    }

    @Override
    public void saveAll(List<Student> students) {
        //todo 这里没做
    }

    @Override
    public void deleteById(String id) {
        dao.delete(id);
    }
}
